package org.dut.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.dut.captcha.Properties.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    //降低代码耦合度，方便后续更改参数
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码并写入响应的输出流
        //考虑多线程的问题，不能将Captcha设置为成员变量
        //为了check的时候能获取Captcha，将Captcha写入Session中
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
        lineCaptcha.write(response.getOutputStream());
        session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());

    }

    @RequestMapping("/check")
    public Boolean checkCaptcha(HttpSession session,String inputCode) {
        if(!StringUtils.hasLength(inputCode)) {
            return false;
        }
        String savedCode = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        if(inputCode.equalsIgnoreCase(savedCode)) {
            return saveDate != null && System.currentTimeMillis() - saveDate.getTime() < captchaProperties.getSession_valid_timeout();
        }
        return false;
    }
}
